<template>
  <div :style="{height: `${theme === 'transparent' ? 0 : '74px'}`}">
    <loginPopup
        v-model="showLoginPopup"
        :default-form="loginPopupDefaultForm"
        @loginSuccess="handleLoginSuccess"
        @registerSuccess="handleRegisterSuccess"
        @close="handleClose"/>
    <div class="nav" :class="`nav--${theme}`">
      <div class="content--left">
        <div
            class="aside-btn"
            v-show="windowWidth <= 900"
            @click="showAsideDrawer = true">
          <v-icon
              size="24"
              :color="textColor">
            fas fa-bars
          </v-icon>
        </div>
        <div class="logo-container">
          <v-btn
              depressed
              text
              plain
              :ripple="false"
              to="/">
            <v-img
                class="logo" alt=""
                :src="require(`@/assets/image/logo_${this.theme === 'light' ? 'dark' : 'light'}.svg`)"/>
          </v-btn>
        </div>
        <div class="items-container">
          <div
              class="item"
              v-for="(item, index) in navigationItemsList"
              :key="item.id"
              :data-nav-item-index="index"
              @mouseenter="handleNavItemMouseEnter"
              @mouseleave="handleNavItemMouseLeave"
              @click="handleNavItemClick(item)">
            {{ item.name }}
            <v-icon
                size="10"
                v-show="item.itemsList"
                @mouseover.native>
              fas fa-chevron-down
            </v-icon>
          </div>
        </div>
      </div>
      <div class="content--right">
        <div class="search-container" v-show="showSearch">
          <div
              class="search-field"
              v-show="windowWidth > 1200">
            <v-text-field
                v-model="searchValue"
                dence
                rounded
                filled
                :dark="theme === 'dark'"
                hide-details
                single-line
                label="搜索课程、讲师……"
                append-icon="fa-search"
                @keydown.enter="doSearch"
                @click:append="doSearch"/>
          </div>
          <div
              class="search-btn"
              v-show="windowWidth <= 1200">
            <v-btn
                icon
                plain
                @click="doSearch"
                :color="theme === 'transparent' ? '#fff' : ''"
                :dark="theme === 'dark'">
              <v-icon
                  class="ma-3"
                  size="24">
                fas fa-search
              </v-icon>
            </v-btn>
          </div>
        </div>
        <div class="user-info-container">
          <div
              v-if="!loginStatus"
              class="login-btn-container">
            <v-btn
                width="80"
                text
                :color="theme === 'transparent' ? '#fff' : ''"
                :dark="theme === 'dark'"
                @click="handleRegister">
              注册
            </v-btn>
            <v-btn
                class="ma-1"
                depressed
                width="80"
                color="primary"
                :dark="theme === 'dark'"
                @click="handleLogin">
              登录
            </v-btn>
          </div>
          <div
              v-else
              class="user-container"></div>
        </div>
      </div>
      <div
          v-show="showFloatingMenu"
          class="floating-menu"
          :class="showFloatingMenu ? 'floating-menu--show' : 'floating-menu--hidden'"
          :style="{left: `${floatingMenuPosition.left}px`}"
          @mouseenter="handleFloatingMenuMouseEnter"
          @mouseover="floatingMenuMouseOver = true"
          @mouseleave="handleFloatingMenuMouseLeave">
        <div
            class="item"
            v-for="item in floatingMenuItemList"
            :key="item.name"
            @click="handleNavItemClick(item)">
          {{ item.name }}
        </div>
      </div>
    </div>
    <v-navigation-drawer
        class="deep-grey"
        v-model="asideDrawerFolding"
        absolute
        temporary
        left
        width="350px"
        :dark="theme === 'dark'">
      <v-list nav flat>
        <v-list-item
            class="v-list-group__header v-list-item v-list-item--link item--home"
            v-ripple
            to="index">
          <v-list-item-content>
            <v-list-item-title v-text="'首页'"></v-list-item-title>
          </v-list-item-content>
        </v-list-item>
        <div
            v-for="item in navigationItemsList"
            :key="item.id">
          <v-list-group v-show="item.itemsList">
            <template v-slot:activator>
              <v-list-item-content>
                <v-list-item-title v-text="item.name"></v-list-item-title>
              </v-list-item-content>
            </template>
            <v-list-item
                class="v-list-item--link"
                v-for="child in item.itemsList"
                :key="child.name"
                v-ripple>
              <v-list-item-content>
                <v-list-item-title v-text="child.name"></v-list-item-title>
              </v-list-item-content>
            </v-list-item>
          </v-list-group>
          <v-list-item
              class="v-list-group__header v-list-item v-list-item--link item--home"
              v-ripple
              v-show="!item.itemsList">
            <v-list-item-content>
              <v-list-item-title v-text="item.name"></v-list-item-title>
            </v-list-item-content>
          </v-list-item>
        </div>
      </v-list>
    </v-navigation-drawer>
    <v-dialog
        v-model="showFeedbackPopup"
        class="rounded-xl"
        width="50vw"
        max-width="700"

        @close="handleCloseFeedbackPopup()">
      <div class="search-user-popup-container">
        <div class="title-text">
          在线反馈
        </div>
        <v-text-field
            label="请输入在线反馈的信息"
            clearable
            v-model="feedbackValue"
            type="text"
        ></v-text-field>
        <div class="my-2 center" style="margin: 0 auto">
          <v-btn
              color="primary"
              dark
              @click="handleSetUpFeedback()"
          >
            提 交
          </v-btn>
        </div>
      </div>
    </v-dialog>
  </div>
</template>

<script>
import loginPopup from "@/components/loginPopup/loginPopup";
import {addFeedBack} from "../../api";

/**
 * @description 导航栏组件
 * @property {String} theme 导航栏主题，支持：light/dark/transparent，默认为light
 * @property {String} search-content 搜索框的值
 * @property {Boolean} showSearch 是否显示搜索组件
 * @event loginSuccess 登陆成功回调事件
 * @event registerSuccess 注册成功回调事件
 * @example <navigationBar theme="dark"/>
 */
export default {
  name: "navigationBar",
  components: {
    loginPopup
  },
  props: {
    theme: {
      type: String,
      default: 'light'
    },
    showSearch: {
      type: Boolean,
      default: true
    },
    searchContent: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      navigationItemsList: [
        {
          id: -1,
          name: '首页',
          href: '/course',
        },
        {
          id: 0,
          name: '视频课程',
          href: '/search?key=&type=0',
          itemsList: [
            {
              id: 0,
              name: '课程搜索',
              href: '/search?key=&type=0'
            }, {
              id: 1,
              name: '讲师搜索',
              href: '/search?key=&type=1'
            }, {
              id: 2,
              name: '畅销课程'
            }, {
              id: 3,
              name: '限时秒杀'
            }
          ]
        }, {
          id: 1,
          name: '题库',
          href: '/myQuestionBank',
          itemsList: [
            {
              id: 0,
              name: '题库',
              href: '/myQuestionBank'
            },
            {
              id: 1,
              name: '在线考试',
              href: '/examOnline'
            },
            {
              id: 2,
              name: '我的证书',
              href: '/myGrade'
            },
          ]
        },
        {
          id: 3,
          name: '专业介绍',
          href: '/majors',
        },
        {
          id: 2,
          name: '博客',
          href: '/blog',
        },
        {
          id: 4,
          name: '个人中心',
          href: '/personalCenter',
          itemsList: [
            {
              id: 0,
              name: '个人中心',
              href: '/personalCenter'
            },
            {
              id: 1,
              name: '聊天',
              href: '/chat'
            },
            {
              id: 2,
              name: '反馈',
              action: 'feedback'
            },
            {
              id: 3,
              name: '退出登录',
              action: "loginOut"
            },
          ]
        }
      ], //导航栏左侧标签列表
      showFloatingMenu: false, //是否显示二级悬浮菜单
      floatingMenuPosition: {
        left: 0,
      }, //二级悬浮菜单位置
      floatingMenuMouseOver: false, //当前鼠标是否悬浮在二级悬浮菜单上
      currentHoverItemIndex: -1, //当前导航栏左侧标签鼠标悬浮的序号
      searchValue: '', //导航栏搜索框的内容
      loginStatus: false, //用户是否已经登陆
      showLoginPopup: false, //是否显示登录弹出窗
      loginPopupDefaultForm: 0, //登录弹出窗默认显示的表单，0:登录，1:注册
      showAsideDrawer: false, //是否显示侧边导航栏
      showFeedbackPopup: false,// 显示反馈的框,
      feedbackValue: "",
      userInfo: {}
    }
  },
  methods: {
    // 导航栏左侧大标签鼠标移入事件
    handleNavItemMouseEnter(e) {
      this.currentHoverItemIndex = Number(e.target.dataset.navItemIndex);
      if (this.navigationItemsList[Number(e.target.dataset.navItemIndex)].itemsList) {
        this.floatingMenuPosition.left = e.target.offsetLeft;
        this.showFloatingMenu = true;
      }
    },
    // 导航栏左侧大标签鼠标移出事件
    handleNavItemMouseLeave(e) {
      if (!this.floatingMenuMouseOver) {
        this.showFloatingMenu = false;
      }
    },
    /**
     * 导航栏标签点击事件
     * @param {Object} item 所点击的标签
     */
    handleNavItemClick(item) {
      console.log(item.name);
      if (!!item.href) {
        this.$router.push(item.href);
      }
      if (!!item.action) {
        if (item.action === "loginOut") {
          this.loginOut()
        } else if (item.action === "feedback") {
          this.handleShowFeedbackPopup();
        }
      }
    },
    // 导航栏二级悬浮菜单鼠标移入事件
    handleFloatingMenuMouseEnter(e) {
      this.showFloatingMenu = true;
    },
    // 导航栏二级悬浮菜单鼠标移出事件
    handleFloatingMenuMouseLeave(e) {
      this.showFloatingMenu = false;
      this.floatingMenuMouseOver = false;
    },
    // 执行搜索操作
    doSearch() {
      this.$emit('search', this.searchValue);
      if (this.$route.path !== '/search') {
        this.$router.push(`/search?key=${this.searchValue}`);
      }
    },
    // 登录按钮点击事件
    handleLogin() {
      this.loginPopupDefaultForm = 0;
      this.showLoginPopup = true;
    },
    // 注册按钮点击事件
    handleRegister() {
      this.loginPopupDefaultForm = 1;
      this.showLoginPopup = true;
    },
    // 登陆成功事件
    handleLoginSuccess() {
      console.log('loginSuccess');
      this.$emit('loginSuccess');
      this.refreshNav()
      this.$router.go(0)
    },
    // 注册成功事件
    handleRegisterSuccess() {
      console.log('registerSuccess');
      this.$emit('registerSuccess');
      this.refreshNav()
      this.$router.go(0)
    },
    handleClose() {
      this.showLoginPopup = false;
      this.$emit('loginClose');
    },
    refreshNav() {
      if (sessionStorage.getItem("userInfo") != null) {
        this.loginStatus = true;
      } else {
        this.loginStatus = false;
        this.navigationItemsList = [
          {
            id: -1,
            name: '首页',
            href: '/course',
          },
          {
            id: 0,
            name: '视频课程',
            href: '/search?key=&type=0',
            itemsList: [
              {
                id: 0,
                name: '课程搜索',
                href: '/search?key=&type=0'
              }, {
                id: 1,
                name: '讲师搜索',
                href: '/search?key=&type=1'
              }, {
                id: 2,
                name: '畅销课程'
              }, {
                id: 3,
                name: '限时秒杀'
              }
            ]
          }, {
            id: 1,
            name: '题库',
            href: '/myQuestionBank',
            itemsList: [
              {
                id: 0,
                name: '题库',
                href: '/myQuestionBank'
              },
              {
                id: 1,
                name: '在线考试',
                href: '/examOnline'
              },
              {
                id: 2,
                name: '我的证书',
                href: '/myGrade'
              }
            ]
          },
          {
            id: 2,
            name: '专业介绍',
            href: '/majors',
          },
          {
            id: 3,
            name: '博客',
            href: '/blog',
          },

        ]
      }
    },
    loginOut() {
      sessionStorage.removeItem("userInfo");
      sessionStorage.removeItem("token");
      this.refreshNav()
      this.$router.go(0)
      this.$message.success('退出登录成功');
    },
    handleShowFeedbackPopup() {
      this.showFeedbackPopup = true
    },
    handleCloseFeedbackPopup() {
      this.showFeedbackPopup = false
      this.feedbackValue = ""
    },
    async handleSetUpFeedback() {
      console.log(this.userInfo)
      let res = await addFeedBack(this.userInfo.id, this.userInfo.username, this.feedbackValue);
      if (res.success) {
        this.$message.success('在线反馈成功');
      } else {
        this.$message.error('在线反馈失败');
      }
      this.handleCloseFeedbackPopup();
    }
  },
  computed: {
    // 文字颜色
    textColor() {
      return this.theme === 'light' ? 'rgb(3,6,13)' : '#fff';
    },
    // 背景颜色
    bgColor() {
      return this.theme === 'dark' ? 'rgb(3,6,13)' : '#fff';
    },
    // 屏幕宽度实时数值
    windowWidth() {
      return this.$store.state.screenWidth + 5;
    },
    // 二级悬浮菜单列表内容
    floatingMenuItemList() {
      if (this.currentHoverItemIndex !== -1) {
        return this.navigationItemsList[this.currentHoverItemIndex].itemsList;
      } else return [];
    },
    // 映射props中的searchContent，强制在值变化时触发监听器
    getSearchContent() {
      return this.searchContent;
    },
    // 侧边导航栏折叠状态
    asideDrawerFolding: {
      get() {
        return this.windowWidth <= 900 ? this.showAsideDrawer : false;
      },
      set(val) {
        this.showAsideDrawer = val;
      }
    },
    userInfo: {
      get() {
        return this.$store.state.userInfo ?? null;
      }
    }
  },
  watch: {
    // 监听props中的getSearchContent的变化，同步到data中的searchValue
    getSearchContent(nval) {
      this.searchValue = nval;
    }
  },
  mounted() {
    this.refreshNav()
    this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
  }
}
</script>

<style lang="scss" scoped>
@import 'navigationBar';
</style>